<?php
namespace App\Services\Mqtt;

use Bluerhinos\phpMQTT;
/**
 * 
 */
class Subscribes extends MqttBase
{
	public function subscribe(string $topic, $client_id, $qos = 0)
	{
		$mqtt = new phpMQTT($this->host, $this->port, $client_id);
		if ($mqtt->connect(true, NULL, $this->username, $this->password)) {
            //$topic  为接受的主题名  需要和发送的主题名一致  否则会订阅不到
	        //订阅信息 Qos为信息登记，需要和发送的等级一致
			$topics[$topic] = array("qos" => $qos, "function" => "on_message");
			
	        $mqtt->subscribe($topics, $qos);

	        //死循环监听
	        while ($mqtt->proc()) {

	        }

	        $mqtt->close();
        } else {
        	return false;    
        }
	}

	function on_message($topic, $msg)
	{
		//我把数据传递到了另一个方法进行处理  可以在处理完逻辑业务之后 再次调用发布方法  去给订阅方发布消息
		cache(['msg' => $msg]);
		cache(['num' => 1]);
	}
}